﻿#include "form2.h"
#include "ui_form2.h"

#include "cairo.h"
#include <QDebug>
#include <QPainter>

#define ANGLE(ang) (ang * 3.1415926 / 180.0) //把角度转换为所对应的弧度

Form2::Form2(QWidget *parent)
    : QWidget(parent),
      ui(new Ui::Form2)
{
    ui->setupUi(this);
}

Form2::~Form2()
{
    delete ui;
}

//https://blog.csdn.net/liu0808/article/details/50297221
//利用Cairo图形库绘制太极图
void Form2::paintEvent(QPaintEvent *pEvent)
{
    Q_UNUSED(pEvent);

    //创建一张图QImage
    int iW = this->width();
    int iH = this->height();
    QImage image(iW, iH, QImage::Format_ARGB32);
    unsigned char *pData = image.bits();
    int iLineStride = image.bytesPerLine();

    const int SIZE = std::min(iW, iH); //太极图大小
    const int CX = (iW / 2);           //太极圆中心横坐标
    const int CY = (iH / 2);           //太极圆中心纵坐标
    const int R = (SIZE / 2);          //太极圆半径

    //cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, SIZE + 1, SIZE + 1);
    cairo_surface_t *surface = cairo_image_surface_create_for_data(pData, CAIRO_FORMAT_ARGB32, iW, iH, iLineStride);
    cairo_t *cr = cairo_create(surface);

    //绘制太极边框
    cairo_set_line_width(cr, 2.0);
    cairo_set_source_rgba(cr, 0, 0, 0, 1);
    cairo_arc(cr, CX, CY, R, ANGLE(0), ANGLE(360));
    cairo_stroke(cr);

    //绘制阴阳圆
    cairo_set_source_rgba(cr, 0, 0, 0, 1);
    cairo_arc(cr, CX, CY, R, ANGLE(90), ANGLE(270));
    cairo_fill(cr);
    cairo_set_source_rgba(cr, 1, 1, 1, 1);
    cairo_arc(cr, CX, CY, R, ANGLE(-90), ANGLE(90));
    cairo_fill(cr);

    //绘制阴阳线
    cairo_set_source_rgba(cr, 0, 0, 0, 1);
    cairo_arc(cr, CX, CY - R / 2, R / 2, ANGLE(-90), ANGLE(90));
    cairo_fill(cr);
    cairo_set_source_rgba(cr, 1, 1, 1, 1);
    cairo_arc(cr, CX, CY + R / 2, R / 2, ANGLE(90), ANGLE(270));
    cairo_fill(cr);

    //绘制太极眼
    cairo_set_source_rgba(cr, 1, 1, 1, 1);
    cairo_arc(cr, CX, CY - R / 2, R / 10, ANGLE(0), ANGLE(360));
    cairo_fill(cr);
    cairo_set_source_rgba(cr, 0, 0, 0, 1);
    cairo_arc(cr, CX, CY + R / 2, R / 10, ANGLE(0), ANGLE(360));
    cairo_fill(cr);

    //将Memory的渲染效果存储到图片中
    cairo_surface_write_to_png(surface, "d:\\taichi.png");

    //销毁并退出Cairo绘图环境
    cairo_destroy(cr);
    cairo_surface_destroy(surface);

    //贴图
    QPainter painter(this);
    painter.drawImage(this->rect(), image);
}
